library("osrm")

## set working directory 
setwd("~/Dropbox/World Bank/OTN_LAC/proj_code")

group = 1 # which connected country group do you want to look at?

# load in file of coordinates for that country, created by prepare_osm_data.m
data <- read.csv(paste0("data/OSMR/connected_coordinates", group,".csv"))

# create row identifier 
data$id <- rownames(data)
data <- data[, c(1, 2, 3, 4, 5)]

# get travel times between points
data$travel_time <- 0
data$travel_distance <- 0
data$speed <- 0

for (i in 1:nrow(data)) {
 result <- osrmRoute(
    src = data[i, c(1, 2, 3)], ## use these
    dst = data[i, c(1, 4, 5)], overview=FALSE) # durations are given in seconds 
 
 # there are some pairs of points through which no routes exist -- no problem 
 if (length(result) ==0) {
   data$travel_time[i] <- NA
   data$travel_distance[i] <-  NA
   data$speed[i] <- NA
 }
 
 else{
   data$travel_time[i] <- result[1]/60
   data$travel_distance[i] <- result[2]
   data$speed[i] <-result[2]/(result[1]/60)
 }
}

# export list of travel times 
write.csv(data, paste0("data/OSMR/connected_coordinates", group , "_wtimes.csv"))



